<?php 
require_once 'init.php';
require_once 'ckLogin.php';
require_once 'dbClasses'.DIRECTORY_SEPARATOR.'config.php';
require_once 'dbClasses'.DIRECTORY_SEPARATOR.'dbConn.php';
$db = new dbConn();

$year = date("Y");
$month = date("m");
$day = date("d");
//$StartTime = "$year-$month-01 00:00:00";
//$days = date("t", strtotime("$year-$month"));
//$EndTime = "$year-$month-$days 23:59:59";
$db->sql="SELECT o.*,a.id,c.`shared`,c.`collected` FROM OrderData o,admin a,((SELECT con.`goodsID`,con.`updater`,con.`publishDate`,con.`shared`,con.`collected` from content con where con.`status`=1) union(SELECT p.`goodsID`,p.`updater`,p.`publishDate`,p.`shared`,p.`collected` from priceninepointnine p where p.`status`=1)) c where o.GoodsId=c.goodsID AND c.updater=a.userName AND month(c.publishDate)=$month AND month(o.CreateTime)=$month";
$OrderData = $db->doResultList2();
$Selecters = array();
if($OrderData){
	$UserId = ($_SESSION['userId'] == 1) ? 4 : $_SESSION['userId'];
	$db->sql="SELECT id,nickName FROM `admin` where `type`=2";
	$users = $db->doResultList2();
	$num = count($users);
	$ShowId = $num+1;
	foreach($users as $key => $user){
		$Selecters[$user['id']] = $user;
		$Selecters[$user['id']]["OrderNum"] = 0;
		$Selecters[$user['id']]["LogNum"] = 0;
		$Selecters[$user['id']]["OrderMon"] = 0;
		$Selecters[$user['id']]["FSNum"] = 0;
		$Selecters[$user['id']]["XlJb"] = 0;
		$Selecters[$user['id']]["XlGx"] = 0;
		$Selecters[$user['id']]["YjJb"] = 0;
		$Selecters[$user['id']]["YjGx"] = 0;
		$Selecters[$user['id']]["FxSc"] = 0;
		$Selecters[$user['id']]["xlw"] = 0;
		$Selecters[$user['id']]["yjw"] = 0;
		$Selecters[$user['id']]["sgw"] = 0;
		$Selecters[$user['id']]["All"] = 0;
		$Selecters[$user['id']]["NumDiff"] = 0;
		$Selecters[$user['id']]["MonDiff"] = 0;
		for($i=1;$i<=$day;$i++){
			$j = ($i<10) ? "0$i" : $i;
			$Selecters[$user['id']]["DayData"]["$year-$month-$j"]['num'] = 0;
			$Selecters[$user['id']]["DayData"]["$year-$month-$j"]['mon'] = 0;
			$Selecters[$user['id']]["DayData"]["$year-$month-$j"]['fsnum'] = 0;
		}
		if($user['id'] == $_SESSION['userId']){
			$ShowId = $key;
		}
	}		
	
	$db->sql="SELECT * FROM `PerformFactor` WHERE time='$year-$month'";
	$factor = $db->doResultList2();
	if(!isset($factor[0])){
		$factor[0]["BasePay"] = 1800;
		$factor[0]["ratio"] = 1;
	}
	//全部奖金
	$qbjj = $num*$factor[0]["BasePay"]*$factor[0]["ratio"];
	//销量级别奖金
	$xljb = $qbjj*0.27;
	//销量贡献奖金
	$xlgx = $qbjj*0.18;
	//佣金级别奖金
	$yjjb = $qbjj*0.27;
	//佣金贡献奖金
	$yjgx = $qbjj*0.18;
	//分享收藏奖金
	$fxsc = $qbjj*0.1;
	foreach($OrderData as $val){
		foreach($Selecters as $key => $item){
			if($key == $val['id']){
				switch($val['CurrentPrice']){
					case ($val['CurrentPrice']<20) : $LogNum = $val["OrderNum"]; break;
					case ($val['CurrentPrice']>=20 && $val['CurrentPrice']<40) : $LogNum = $val["OrderNum"] * 1.2; break;
					case ($val['CurrentPrice']>=40 && $val['CurrentPrice']<60) : $LogNum = $val["OrderNum"] * 1.4; break;
					case ($val['CurrentPrice']>=60 && $val['CurrentPrice']<80) : $LogNum = $val["OrderNum"] * 1.6; break;
					case ($val['CurrentPrice']>=80 && $val['CurrentPrice']<100) : $LogNum = $val["OrderNum"] * 1.8; break;
					case ($val['CurrentPrice']>=100) : $LogNum = $val["OrderNum"] * 2; break;
				}
				$Selecters[$key]['OrderNum'] += $val["OrderNum"];
				$Selecters[$key]['LogNum'] += $LogNum;
				$mon = round($val["OrderNum"]*$val["CurrentPrice"]*trim($val["OrderRate"], "%")*0.01, 2);
				$Selecters[$key]["OrderMon"] += $mon;
				$Selecters[$key]["FSNum"] += ($val["shared"] + $val["collected"]);
				$time = substr($val['CreateTime'], 0, 10);
				$Selecters[$key]["DayData"]["$time"]["num"] += $LogNum;
				$Selecters[$key]["DayData"]["$time"]["mon"] += $mon;
				$Selecters[$key]["DayData"]["$time"]["fsnum"] += ($val["shared"] + $val["collected"]);
			}
		}
	}
	$AllOrderNum = 0;
	$AllOrderMon = 0;
	$AllFSNum = 0;
	$SumNum = 0;
	for($i=1;$i<=$num;$i++){
		$SumNum += $i;
	}
	foreach($Selecters as $key => $val){
		$AllOrderNum += $val['LogNum']; 
		$AllOrderMon += $val['OrderMon']; 
		$AllFSNum += $val['FSNum']; 
		$OrderNum[$key] = $val['LogNum'];
		$OrderMon[$key] = $val['OrderMon']; 
		$FSNum[$key] = $val['FSNum'];
	}
	$YjLastId = 0;
	$XlLastId = 0;
	$XlLtId = 0;
	$YjLtId = 0;
	
	arsort($OrderNum);
	arsort($OrderMon);
	arsort($FSNum);
	GetSort($OrderNum, "Selecters", "NumSort", $num);
	GetSort($OrderMon, "Selecters", "MonSort", $num);
	GetSort($FSNum, "Selecters", "FSSort", $num);
	foreach($Selecters as $key => $val){
		if($key == $XlLastId || $key == $XlLtId){
			$Selecters[$key]["XlJb"] = 0;
			$Selecters[$key]["XlGx"] = 0;
		}
		else{
			$Selecters[$key]["XlJb"] = round(($num-$val["NumSort"]+1)/$SumNum*$xljb, 2);		
			$Selecters[$key]["XlGx"] = round($val['LogNum']/$AllOrderNum*$xlgx, 2);
		}
		if($key == $YjLastId || $key == $YjLtId){
			$Selecters[$key]["YjJb"] = 0;
			$Selecters[$key]["YjGx"] = 0;
		}
		else{
			$Selecters[$key]["YjJb"] = round(($num-$val["MonSort"]+1)/$SumNum*$yjjb, 2);
			$Selecters[$key]["YjGx"] = round($val['OrderMon']/$AllOrderMon*$yjgx, 2);
		}
		$Selecters[$key]["FxSc"] = round($val["FSNum"]/$AllFSNum*$fxsc, 2);
	}
	
	foreach($Selecters as $key => $val){
		$Selecters[$key]["All"] = $val["XlJb"]+$val["YjJb"]+$val["XlGx"]+$val["YjGx"]+$val["FxSc"];
		if($val["NumSort"] == 1){
			$Selecters[$key]["xlw"] = 100;
			$Selecters[$key]["All"] += $Selecters[$key]["xlw"];
		}
	
		if($val["MonSort"] == 1){
			$Selecters[$key]["yjw"] = 100;
			$Selecters[$key]["All"] += $Selecters[$key]["yjw"];
		}
		
		if($val["NumSort"] == 1 && $val["MonSort"] == 1){
			$Selecters[$key]["sgw"] = 100;
			$Selecters[$key]["All"] += $Selecters[$key]["sgw"];
		}
	}
	//var_dump($Selecters);exit;
	$NumSort = sortArrayDesc($Selecters, "LogNum");
	$MonSort = sortArrayDesc($Selecters, "OrderMon");
	$FSSort = sortArrayDesc($Selecters, "FSNum");
	$MonthStr = "'$month-01'";
	for($i=2;$i<=$day;$i++){
		$j = ($i<10) ? "0$i" : $i;
		$MonthStr .= ",'$month-$j'";
	}
	
	$SeriesStr = "";
	$SeriesStr2 = "";
	$SeriesStr3 = "";
	foreach($NumSort as $val){
		$SeriesStr .= "{name: '{$val['nickName']}',data: [";		
		foreach($val["DayData"] as $item){
			$SeriesStr .= "{$item['num']},";			
		}
		$SeriesStr = trim($SeriesStr, ",");		
		$SeriesStr .= "]},";		
	}
	
	foreach($MonSort as $val){
		$SeriesStr2 .= "{name: '{$val['nickName']}',data: [";
		foreach($val["DayData"] as $item){			
			$SeriesStr2 .= "{$item['mon']},";
		}		
		$SeriesStr2 = trim($SeriesStr2, ",");		
		$SeriesStr2 .= "]},";
	}
	
	foreach($FSSort as $val){
		$SeriesStr3 .= "{name: '{$val['nickName']}',data: [";
		foreach($val["DayData"] as $item){
			$SeriesStr3 .= "{$item['fsnum']},";
		}
		$SeriesStr3 = trim($SeriesStr3, ",");
		$SeriesStr3 .= "]},";
	}
}

function GetSort($odata, $ndata, $param, $num){
	$i = 1;
	global ${$ndata},$YjLastId,$XlLastId,$XlLtId,$YjLtId;
	$LastKey = 0;
	foreach($odata as $key => $val){
		${$ndata}[$key][$param] = $i;
		if($LastKey && $param=="NumSort"){
			${$ndata}[$key]["NumDiff"] = round((${$ndata}[$LastKey]["LogNum"] - ${$ndata}[$key]["LogNum"]), 2);
		}
		elseif($LastKey && $param=="MonSort"){
			${$ndata}[$key]["MonDiff"] = round((${$ndata}[$LastKey]["OrderMon"] - ${$ndata}[$key]["OrderMon"]), 2);
		}		
		if($i==$num && $param=="NumSort"){
			$XlLastId = $key;
		}
		elseif($i==($num-1) && $param=="NumSort"){
			$XlLtId = $key;
		}
		elseif($i==$num && $param=="MonSort"){
			$YjLastId = $key;
		}
		elseif($i==($num-1) && $param=="MonSort"){
			$YjLtId = $key;
		}
		$LastKey = $key;
		$i++;
	}
}
//按$sortType关键字降序
function sortArrayDesc($preData, $sortType='newPrice'){
	$sortData = array();
	foreach ($preData as $key_i => $value_i){
		$price_i = $value_i[$sortType];
		$min_key = '';
		$sort_total = count($sortData);
		foreach ($sortData as $key_j => $value_j){
			if($price_i>$value_j[$sortType]){
				$min_key = $key_j+1;
				break;
			}
		}
		if(empty($min_key)){
			array_push($sortData, $value_i);
		}else {
			$sortData1 = array_slice($sortData, 0,$min_key-1);
			array_push($sortData1, $value_i);
			if(($min_key-1)<$sort_total){
				$sortData2 = array_slice($sortData, $min_key-1);
				foreach ($sortData2 as $value){
					array_push($sortData1, $value);
				}
			}
			$sortData = $sortData1;
		}
	}
	return $sortData;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simpla Admin</title>
<!--                       CSS                       -->
<!-- Reset Stylesheet -->
<link rel="stylesheet" href="resources/css/reset.css" type="text/css"
	media="screen" />
<!-- Main Stylesheet -->
<link rel="stylesheet" href="resources/css/main.css" type="text/css"
	media="screen" />
<!-- Invalid Stylesheet. This makes stuff look pretty. Remove it if you want the CSS completely valid -->
<link rel="stylesheet" href="resources/css/invalid.css" type="text/css"
	media="screen" />
<link rel="stylesheet" type="text/css" href="resources/css/default.css" />
<!--                       Javascripts                       -->
<!-- jQuery -->
<script type="text/javascript" src="resources/scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function () {
	 var chart;
	 var chart2;
	 var chart3;
	    $(document).ready(function() {
	        chart = new Highcharts.Chart({
	            chart: {
	                renderTo: 'container',
	                type: 'line'
	            },
	            title: {
	                text: '销量排名',
	                x: -20 //center
	            },
	            subtitle: {
	                text: '<?php echo "$year-$month-01 至 $year-$month-$day";?>',
	                x: -20
	            },
	            exporting:{ 
                    enabled: false 
               },
	            xAxis: {
	                categories: [<?php echo $MonthStr;?>],
	                labels: {
		                rotation: 80
	                }
	            },
	            yAxis: {
	                title: {
	                    text: '排名'
	                },
	                plotLines: [{
	                    value: 0,
	                    width: 1,
	                    color: '#808080'
	                }]
	            },
	            tooltip: {
	                formatter: function() {
	                        return '<b>'+ this.series.name +'</b><br/>'+
	                        this.x +': '+ this.y+"单";
	                }
	            },
	            series: [<?php echo $SeriesStr;?>]
	        });

	        /*
	        var series = chart.series;   
			$.each(series, function(i,val){      
				if(i!=<?php echo $ShowId;?>){   
					val.hide();
				}
		    });	
		    */ 

			chart2 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'container2',
	                type: 'line'
	            },
	            title: {
	                text: '佣金排名',
	                x: -20 //center
	            },
	            subtitle: {
	                text: '<?php echo "$year-$month-01 至 $year-$month-$day";?>',
	                x: -20
	            },
	            exporting:{ 
                    enabled: false 
               },
	            xAxis: {
	                categories: [<?php echo $MonthStr;?>],
	                labels: {
		                rotation: 80
	                }
	            },
	            yAxis: {
	                title: {
	                    text: '排名'
	                },
	                plotLines: [{
	                    value: 0,
	                    width: 1,
	                    color: '#808080'
	                }]
	            },
	            tooltip: {
	                formatter: function() {
	                        return '<b>'+ this.series.name +'</b><br/>'+
	                        this.x +': '+ this.y+"元";
	                }
	            },
	            series: [<?php echo $SeriesStr2;?>]
	        });

			/*
			var series2 = chart2.series;   
			$.each(series2, function(i,val){      
				if(i!=<?php echo $ShowId;?>){   
					val.hide();
				}
			});
			*/	

			chart3 = new Highcharts.Chart({
	            chart: {
	                renderTo: 'container3',
	                type: 'line'
	            },
	            title: {
	                text: '分享收藏排名',
	                x: -20 //center
	            },
	            subtitle: {
	                text: '<?php echo "$year-$month-01 至 $year-$month-$day";?>',
	                x: -20
	            },
	            exporting:{ 
                    enabled: false 
               },
	            xAxis: {
	                categories: [<?php echo $MonthStr;?>],
	                labels: {
		                rotation: 80
	                }
	            },
	            yAxis: {
	                title: {
	                    text: '排名'
	                },
	                plotLines: [{
	                    value: 0,
	                    width: 1,
	                    color: '#808080'
	                }]
	            },
	            tooltip: {
	                formatter: function() {
	                        return '<b>'+ this.series.name +'</b><br/>'+
	                        this.x +': '+ this.y+"次";
	                }
	            },
	            series: [<?php echo $SeriesStr3;?>]
	        });
	       
	    })	       
})
</script>
<!-- jQuery Configuration -->
<script type="text/javascript" src="resources/scripts/simpla.jquery.configuration.js"></script>
<!-- Facebox jQuery Plugin -->
<script type="text/javascript" src="resources/scripts/facebox.js"></script>
<!-- jQuery WYSIWYG Plugin -->
<script type="text/javascript" src="resources/scripts/jquery.wysiwyg.js"></script>
<!-- jQuery my97datepicker -->
<script type="text/javascript" src="resources/scripts/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="resources/scripts/highcharts.js"></script>
<script type="text/javascript" src="resources/scripts/exporting.js"></script>
</head>
<body>
	<div id="body-wrapper">
		<!-- Wrapper for the radial gradient background -->		
		<div id="main-content">
			<!-- Main Content Section with everything -->
			<!-- Page Head -->
			<h2>欢迎使用<?php echo APPLICATION;?>管理后台</h2>
			<p id="page-intro">接下来你要做什么呢亲？</p>
			<div class="clear"></div>
			<!-- End .clear -->
			<div class="content-box">
				<!-- Start Content Box -->
				<div class="content-box-header">
					<h3>用户绩效</h3>
					<!-- <ul class="content-box-tabs">
						<li><a href="#tab1" class="default-tab">Table</a></li>
						href must be unique and match the id of target div
						<li><a href="#tab2">Forms</a></li>
					</ul> -->
					<div class="clear"></div>
				</div>
				<!-- End .content-box-header -->
				<div class="content-box-content">			
					<div class="tab-content default-tab">
					<?php if($_SESSION["type"]!=0 && isset($Selecters[$UserId])):?>
						<div class="top">
					    	<p>亲爱的<span class="red" style="margin-left: 10px;"><?php echo $Selecters[$UserId]["nickName"];?></span>，您本月的业绩：</p>
					        <div class="fclear">
					        	<div class="fleft">
					        		<p>真实销量：<span><?php echo $Selecters[$UserId]["OrderNum"];?></span></p>
					        		<p>逻辑销量：<span><?php echo $Selecters[$UserId]["LogNum"];?></span></p>
					            	<p>佣金：<span><?php echo $Selecters[$UserId]["OrderMon"];?></span></p>
					            </div>
					            <div class="fright">
					            	<p>
					            		当前排名<span class="red"><?php echo $Selecters[$UserId]["NumSort"];?></span>，
					            		<?php if($Selecters[$UserId]["NumSort"] == 1):?>
					            			我是销量王，我骄傲！<img style="vertical-align: top;" src="resources/images/honour.gif">
					            		<?php elseif($Selecters[$UserId]["NumSort"] == $num):?>
					            			一不小心成了吊车尾，爆发吧，骚年！<img style="vertical-align: top;" src="resources/images/fight.gif">
					            		<?php else:?>
					                		距离第<?php echo $Selecters[$UserId]["NumSort"]-1;?>名还有<span class="red"><?php echo $Selecters[$UserId]["NumDiff"];?>单</span>					                		
					                	<?php endif;?>
					                </p>
					                <p>
					                	当前排名<span class="red"><?php echo $Selecters[$UserId]["MonSort"];?></span>，
					                	<?php if($Selecters[$UserId]["MonSort"] == 1):?>
					                		我是佣金王，我骄傲！<img style="vertical-align: top;" src="resources/images/honour.gif">
					                	<?php elseif($Selecters[$UserId]["MonSort"] == $num):?>
					                		一不小心成了吊车尾，爆发吧，骚年！<img style="vertical-align: top;" src="resources/images/fight.gif">
					                	<?php else:?>
					                		距离第<?php echo $Selecters[$UserId]["MonSort"]-1;?>名还有<span class="red"><?php echo $Selecters[$UserId]["MonDiff"];?>元</span></p>
					            		<?php endif;?>
					            </div>
					        </div>					    
					        <p>预计您本月的奖金：<?php echo $Selecters[$UserId]["All"];?>元</p>
					    </div>
					 <?php endif;?>
					    <div class="middle">
					    	<div class="list_table table_left">
					        	<h3 class="title">销量排行榜</h3>
					            <table class="detail">
					            	<thead>
					            		<tr>
					            			<th></th>
					            			<th>姓名</th>
					            			<th>销量</th>
					            			<th>销量级别奖</th>
					            			<th>销量贡献奖</th>
					            		</tr>
					            	</thead>
					                <tbody>
					                <?php foreach($NumSort as $key => $val):?>
					                	<tr <?php echo ($val['id']==$UserId) ? "class='show'":"";?>>
					                		<td><?php echo $key+1;?>、</td>
					                		<td><?php echo $val['nickName'];?></td>
					                		<td><?php echo $val['LogNum'];?></td>
					                		<td><?php echo $val['XlJb'];?></td>
					                		<td><?php echo $val['XlGx'];?></td>
					                	</tr>
					                <?php endforeach;?>
					                </tbody>
					            </table>
					        </div>
					        <div class="list_table">
					        	<h3 class="title">佣金排行榜</h3>
					            <table class="detail">
					            	<thead>
					            		<tr>
					            			<th></th>
					            			<th>姓名</th>
					            			<th>佣金</th>
					            			<th>佣金级别奖</th>
					            			<th>佣金贡献奖</th>
					            		</tr>
					            	</thead>
					                <tbody>
					                <?php foreach($MonSort as $key => $val):?>
					                	<tr <?php echo ($val['id']==$UserId) ? "class='show'":"";?>>
					                		<td><?php echo $key+1;?>、</td>
					                		<td><?php echo $val['nickName'];?></td>
					                		<td><?php echo $val['OrderMon'];?></td>
					                		<td><?php echo $val['YjJb'];?></td>
					                		<td><?php echo $val['YjGx'];?></td>
					                	</tr>
					                <?php endforeach;?>
					                </tbody>
					            </table>
					        </div>
					        <div class="list_table table_left">
					        	<h3 class="title">分享收藏排行榜</h3>
					            <table class="detail">
					            	<thead>
					            		<tr>
					            			<th></th>
					            			<th>姓名</th>
					            			<th>分享收藏量</th>
					            			<th>分享收藏量奖</th>					            			
					            		</tr>
					            	</thead>
					                <tbody>
					                <?php foreach($FSSort as $key => $val):?>
					                	<tr <?php echo ($val['id']==$UserId) ? "class='show'":"";?>>
					                		<td><?php echo $key+1;?>、</td>
					                		<td><?php echo $val['nickName'];?></td>
					                		<td><?php echo $val['FSNum'];?></td>
					                		<td><?php echo $val['FxSc'];?></td>					                		
					                	</tr>
					                <?php endforeach;?>
					                </tbody>
					            </table>
					        </div>
					    </div>
					    <div class="clear"></div>
						<div id="container" style="min-width: 400px; width:850px; height: 400px; margin: 50px 0 0 20px;"></div>
						<div id="container2" style="min-width: 400px; width:850px; height: 400px; margin: 50px 0 0 20px;"></div>
						<div id="container3" style="min-width: 400px; width:850px; height: 400px; margin: 50px 0 0 20px;"></div>
					</div>
					<!-- End #tab1 -->
				</div>
				<!-- End .content-box-content -->
			</div>
			<!-- End .content-box -->
			<div class="clear"></div>
			<div id="footer">
				<small> <!-- Remove this notice or replace it with whatever you want -->
					&#169; Copyright 2009 Your Company | Powered by <a
					href="http://themeforest.net/item/simpla-admin-flexible-user-friendly-admin-skin/46073">Simpla
						Admin</a> | <a href="#">Top</a>
				</small>
			</div>
			<!-- End #footer -->
		</div>
		<!-- End #main-content -->
	</div>
</body>
<!-- Download From www.exet.tk-->
</html>